import cgi
#import datetime

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>')

        user = users.get_current_user()
        if user:
            self.response.out.write("<p>Welcome, %s! (<a href=\"%s\">sign out</a>)</p>" %
                  (user.nickname(), users.create_logout_url("/")))
        else:
            self.response.out.write("<p>Sign in or <a href=\"%s\">register</a>.</p>" %
                  users.create_login_url("/"))

        # Write the submission from and the footer of the page
        #if user:
        self.response.out.write("""
            <form action="/sign" method="post">
            <div><textarea name="content" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Signe Guestbook"</div>
            </form>
            </body></html>
            """)

        greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 50")
        # greetings = Greeting.gql("ORDER BY date DESC LIMIT 10")
        # greetings = Greeting.gql("WHERE author = :1 ORDER BY date DESC LIMIT 10", user)

        for greeting in greetings:
            if greeting.author:
                self.response.out.write('%s :: <b>%s</b> wrote :' %
                                    (greeting.date.ctime(),
                                    greeting.author.nickname()))
            else:
                self.response.out.write('An anonyme person wrote:')
                self.response.out.write('<blockquote>%s</blockquote>' %
                                  cgi.escape(greeting.content))

class Guestbook(webapp.RequestHandler):
    def post(self):
        greeting = Greeting()
        user = users.get_current_user()
        if user:
            greeting.author = user
            greeting.content = self.request.get('content')
            greeting.put()
            self.redirect('/')
        else:
            self.redirect(users.create_login_url("/"))

application = webapp.WSGIApplication(
      [('/', MainPage),
       ('/sign', Guestbook)],
      debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()